<template>
  <div class="box">
    <wxlogin
      id="wxcode"
      :appid="appid"
      :scope="scope"
      :redirect_uri="encodeURIComponent(redirect_uri)"
    ></wxlogin>
  </div>
</template>

<script>
import wxlogin from "vue-wxlogin";

export default {
  components: {
    wxlogin,
  },
  data() {
    return {
      wxCode: "",
      self_redirect: false,
      id: "wxcode",
      appid: "wx30894a89a4d7635c",
      scope: "snsapi_login",
      redirect_uri: "http://www.huanchenxinnengyuan.com", //重定向地址，需要进行UrlEncode
      state: "", //可设置为简单的随机数加 session 进行校验
      style: "black",
      href: "", //自定义样式链接，第三方可根据实际需求覆盖默认样式
    };
  },
  mounted() {
  },
  watch: {
    //监听路由可以检测返回的code
    $route: {
      handler: function (route) {
        console.log(this.$route);
        this.wxCode = this.$route.query.code || "";
        //本地存储code是因为从其他页面返回vue页面存在缓存需要自定义刷新
        if (this.wxCode == localStorage["wxCode"] && this.wxCode != "") {
          window.location.href = this.redirect_uri; //回调地址
        } else {
          localStorage.setItem("wxCode", this.wxCode); //设置b为"isaac"
        }
        if (this.wxCode) {
          let params = {
            code: this.wxCode,
            state: "",
          };
          wechatLogin(params)
            .then((res) => {
              if (res.status) {
                //返回参数如果绑定微信返回token正常存储登录未绑定账号返回unionid绑定当然也可以以微信信息为主题自动生成账号
              }
            })
            .catch(() => {
              //返回失败因为二维码已经被使用过所以需要刷新重新获取
              window.location.href = this.redirect_uri;
            });
        }
      },
      // immediate: true,
      deep: true,
    },
  },
  methods: {},
};
</script>
<style scoped>
.box {
  border: 1px solid red;
}
</style>
